#coding=utf-8
import getopt,sys,os
from device import Device
from task import Task
from configobj import ConfigObj
from datetime import datetime
from uploadresult import UploadResult
from devicectrl import DeviceCtrl,KeyCodes



'''''''''''''''''''''''''''''''''''''''''''''
自定义Monkey命令 执行monkey测试，上传测试数据
teky
'''''''''''''''''''''''''''''''''''''''''''''
v_version = 'V0.19.5.5'

def print_version():
    print('====================================================')
    print('>>>>>>>>>        MonkeyTest 版本 %s  <<<<<<<<'% v_version)
    print('====================================================')

def print_help():
    '''打印help'''
    print_version()
    print('调用示例:python start.py -c config')
    print('自动获取连接手机的项目名称和版本名称 deviceid')
    print('----------------参数说明------------------------------')
    print('参数 -c 配置文件名称，例如-c config就会读取config.ini中的配置')

def createfolder():
    '''创建文件夹'''
    #建立报告和截图文件夹
    screen_save_path = sys.path[0] + '/screenshots/'
    reports_path = sys.path[0] + '/reports/'
    monkey_path = sys.path[0] + '/monkeylogs/'


    if not os.path.exists(screen_save_path):
        os.makedirs(screen_save_path)

    if not os.path.exists(reports_path):
        os.makedirs(reports_path)

    if not os.path.exists(monkey_path):
        os.makedirs(monkey_path)

    #利用HtmlReport3生成可视测试报告开始循环执行用例

    retportname = deviceid + '_' + datetime.now().strftime('%Y_%m_%d_%H_%M_%S') + '.html'
    reportfile = reports_path + retportname
    return (retportname, reportfile)

if __name__ == '__main__':

    args_config = 'config'#配置文件名称
    args_debug = True
    args_deviceid = None
    args_apkversion = None
    args_index = 0#默认连接第一个手机

    opts, args = getopt.getopt(sys.argv[1:],"c:")
    for op, value in opts:
        if op == '-c':
            args_config = value

    inipath = sys.path[0] + '/' + args_config + '.ini'


    if not os.path.exists(inipath):
        print('！！！没有找到配置文件' + inipath)
        sys.exit(1)

    config = ConfigObj(inipath, encoding = 'UTF8')
    if os.path.exists(inipath):
        args_modulename= config['配置']['模块']
        args_apkversion = config['配置']['应用版本号']
        args_tester = config['配置']['测试人员']
        args_debug = config['配置']['调试']
        args_package = config['配置']['包名']
        args_events = config['配置']['事件数']
        args_throttle = config['配置']['间隔时间']
        args_seed = config['配置']['随机数值']
        if args_debug == '关':
            args_debug = False
        else:
            args_debug = True

    if args_tester is None:
        print('！！！请填写测试人员姓名')
        sys.exit(1)
    if args_modulename is None:
        print('！！！请填写测试模块')
        sys.exit(1)

    if args_apkversion is None:
        print('！！！请填写模块版本号')
        sys.exit(1)

    print_version()

    #没有指定连接第一个设备
    dev = Device(default_deviceid = args_deviceid, default_index = args_index)
    deviceid = dev.tryConnect()

    if deviceid is None:#没有找到连接手机
        sys.exit(1)
    else:
        devctrl =  DeviceCtrl(deviceid)
        version = devctrl.getversion()
        productname = devctrl.getproductname()
        retportname, reportfile = createfolder()
        test_start_time = datetime.now()
        result = Task(deviceid, args_apkversion, args_package, args_events, args_throttle, args_seed, reportfile).start()
        test_end_time = datetime.now()
        if not args_debug:
            uploadrt = UploadResult(deviceid, result, args_modulename, productname, version, args_apkversion, args_tester, test_start_time, test_end_time, retportname)
            uploadrt.postdata() #调试时候不用开启，正式测试开启上传测试结果数据
            uploadrt.upload_file(reportfile) #调试时候不用开启，正式测试开启上传测试报告
